package com.aerozhonghuan.logisticsmall.modules.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.Group;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.aerozhonghuan.location.ZhLocationCallback;
import com.aerozhonghuan.location.ZhLocationUtils;
import com.aerozhonghuan.location.bean.ZhLocationBean;
import com.aerozhonghuan.logisticsmall.R;
import com.aerozhonghuan.logisticsmall.framework.base.TitlebarFragment;
import com.aerozhonghuan.logisticsmall.modules.order.beans.StoreBean;
import com.aerozhonghuan.logisticsmall.modules.order.logic.OrderWebRequest;
import com.aerozhonghuan.logisticsmall.widget.ProgressDialogIndicator;
import com.aerozhonghuan.oknet2.CommonCallback;
import com.aerozhonghuan.oknet2.CommonMessage;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;

/**
 * Created by ChenLin on 2019/5/25 14:27.Email&WeChat:7877409@163.com
 * 选择服务网点页面
 */
public class SelectStoreFragment extends TitlebarFragment {

    private List<StoreBean.StoreInfo> mStoreInfoList;
    private View rootView;
    private Group mNoInfoTipView;
    private RecyclerView mRecyclerView;
    private Button mBtn;
    private MyRvAdapter mAdapter;
    private String mStoreInfo_name;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_select_store, null);
            initView();
            initData();
        }
        return rootView;
    }

    private void initView() {
        rootView.findViewById(R.id.group_city_select).setVisibility(View.GONE);//本期不做城市选择
        mNoInfoTipView = (Group) rootView.findViewById(R.id.area_no_address_tip);
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.rv);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new MyRvAdapter();
        mRecyclerView.setAdapter(mAdapter);
        mBtn = (Button) rootView.findViewById(R.id.btn);
        mBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelectStoreFragment.this.getActivity().finish();
            }
        });
        mBtn.setEnabled(false);
        ImageView ivArrowDown = (ImageView) rootView.findViewById(R.id.iv_arrow_down);
        ImageView ivArrowPro = (ImageView) rootView.findViewById(R.id.iv_arrow_province);
        TextView tvCity = (TextView) rootView.findViewById(R.id.tv_city);
        TextView tvProvince = (TextView) rootView.findViewById(R.id.tv_province);
        View viewSelect = rootView.findViewById(R.id.view_select);
    }

    private void initData() {
        ZhLocationUtils zhLocationUtils = new ZhLocationUtils();
        zhLocationUtils.startLocation(getContext(), new ZhLocationCallback() {
            @Override
            public void onSuccess(ZhLocationBean zhLocationBean) {
                LogUtils.i("当前经纬度:", zhLocationBean.lat, zhLocationBean.lon);
                requestStoreInfo(zhLocationBean);
            }

            @Override
            public void onFailure() {
                ToastUtils.showShort("定位失败");
            }
        });
    }

    private void requestStoreInfo(ZhLocationBean bean) {
        OrderWebRequest.storesInfoRequest(
                (bean.lat + "").replace(".", ""),
                (bean.lon + "").replace(".", ""),
                getActivity(), new ProgressDialogIndicator(getActivity()), new CommonCallback<StoreBean>() {
                    @Override
                    public void onSuccess(StoreBean messsageBodyObject, CommonMessage commonMessage, String allResponseString) {
                        mStoreInfoList = messsageBodyObject.datalist;
                        setData();
                        for (StoreBean.StoreInfo storeInfo : mStoreInfoList) {
                            if (storeInfo.name.equals(mStoreInfo_name)) {
                                storeInfo.isUserSelected = true;
                                break;
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                });
    }

    private void setData() {
        if (ObjectUtils.isEmpty(mStoreInfoList)) {
            mBtn.setEnabled(false);
            mNoInfoTipView.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
        } else {
            mNoInfoTipView.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mStoreInfo_name = SPUtils.getInstance().getString("StoreInfo_name");
        if (StringUtils.isEmpty(mStoreInfo_name)) {
            mBtn.setEnabled(false);
        } else {
            mBtn.setEnabled(true);
        }
    }

    private void delete() {
        SPUtils.getInstance().remove("StoreInfo_distance");
        SPUtils.getInstance().remove("StoreInfo_address");
        SPUtils.getInstance().remove("StoreInfo_name");
        SPUtils.getInstance().remove("StoreInfo_contactNumber");
        SPUtils.getInstance().remove("StoreInfo_id");
    }

    private void save(StoreBean.StoreInfo info) {
        SPUtils.getInstance().put("StoreInfo_distance", info.distance);
        SPUtils.getInstance().put("StoreInfo_address", info.address);
        SPUtils.getInstance().put("StoreInfo_name", info.name);
        SPUtils.getInstance().put("StoreInfo_contactNumber", info.contactNumber);
        SPUtils.getInstance().put("StoreInfo_id", info.id);
    }

    class MyRvAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyHolder(View.inflate(SelectStoreFragment.this.getContext(), R.layout.item_for_select_store, null));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            ((MyHolder) holder).setData(mStoreInfoList.get(position), position);
        }

        @Override
        public int getItemCount() {
            return ObjectUtils.isEmpty(mStoreInfoList) ? 0 : mStoreInfoList.size();
        }
    }

    class MyHolder extends RecyclerView.ViewHolder {
        private View mViewPlaceholder;
        private TextView mTvAddress;
        private TextView mTvDistance;
        private TextView mTvName;
        private TextView mTvPhoneNumber;
        private ImageView mIvSelect;
        private int position;

        MyHolder(View itemView) {
            super(itemView);
            itemView.findViewById(R.id.temp_view).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(SelectStoreFragment.this.getContext(), StationLocationAcrivity.class).putExtra("StoreInfo", mStoreInfoList.get(position));
                    ActivityUtils.startActivity(intent);
                }
            });
            mViewPlaceholder = itemView.findViewById(R.id.view_placeholder);
            mTvAddress = (TextView) itemView.findViewById(R.id.tv_address);
            mTvDistance = (TextView) itemView.findViewById(R.id.tv_distance);
            mTvName = (TextView) itemView.findViewById(R.id.tv_name);
            mTvPhoneNumber = (TextView) itemView.findViewById(R.id.tv_phone_number);
            mIvSelect = (ImageView) itemView.findViewById(R.id.iv_select);
            mIvSelect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    StoreBean.StoreInfo info = mStoreInfoList.get(position);
                    if (info.isUserSelected) {
                        for (StoreBean.StoreInfo storeInfo : mStoreInfoList) {
                            storeInfo.isUserSelected = false;
                        }
                        delete();
                    } else {
                        info.isUserSelected = true;
                        for (int i = 0; i < mStoreInfoList.size(); i++) {
                            LogUtils.i(i, position);
                            if (i != position) {
                                mStoreInfoList.get(i).isUserSelected = false;
                            }
                        }
                        save(info);
                    }
                    mAdapter.notifyDataSetChanged();
                    for (StoreBean.StoreInfo storeInfo : mStoreInfoList) {
                        if (storeInfo.isUserSelected) {
                            mBtn.setEnabled(true);
                            break;
                        } else {
                            mBtn.setEnabled(false);
                        }
                    }
                }
            });
        }

        public void setData(StoreBean.StoreInfo storeInfo, int position) {
            this.position = position;
            if (mStoreInfoList.size() >= 1 && mStoreInfoList.size() - 1 == position) {
                mViewPlaceholder.setVisibility(View.GONE);
            } else {
                mViewPlaceholder.setVisibility(View.VISIBLE);
            }
            mTvAddress.setText(storeInfo.address);

            DecimalFormat df = new DecimalFormat("#.0");
            if (storeInfo.distance < 1000) {
                df = new DecimalFormat("0.0");
            }
            df.format(new BigDecimal(storeInfo.distance));
            mTvDistance.setText(df.format(new BigDecimal(((long) storeInfo.distance) * 1.0 / 1000)) + "km");

            mTvName.setText(storeInfo.name);
            mTvPhoneNumber.setText(storeInfo.contactNumber);

            if (storeInfo.isUserSelected) {
                mIvSelect.setImageResource(R.mipmap.selected);
            } else {
                mIvSelect.setImageResource(R.mipmap.un_select);
            }
        }
    }
}
